package org.grow.auth.controller;

import org.grow.auth.dao.AccountRepository;
import org.grow.auth.dao.UserInfoRepository;
import org.grow.auth.entity.Account;
import org.grow.auth.entity.UserInfo;
import org.grow.auth.entity.UserRegDto;
import org.grow.auth.service.CommonRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 2022/2/11
 */

@RestController
@RequestMapping("/auth/account")
public class AccountController {

    @Autowired
    private CommonRemote commonRemote;
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @PostMapping("/reg")
    public Boolean reg(@RequestBody UserRegDto userRegDto) {
//        yanzheng accountid weiyi
        ;
//验证username是否存在 验证数据符合正则
//        一旦远程调用失败 回滚整个
//        account.getUsername()
        Account account = new Account();
        System.out.println(userRegDto);
        account.setUsername(userRegDto.getUsername());
        account.setPassword(passwordEncoder.encode(userRegDto.getPassword()));
        Account save = accountRepository.save(account);
        UserInfo userInfo = new UserInfo();
        userInfo.setAccountId(save.getAccountId());
        String nick;
        try {
            nick = save.getUsername().substring(0, 4);
        } catch (Exception e) {
            nick = save.getUsername();
        }
        userInfo.setNickname(userRegDto.getNickname());
        userInfo.setMale(userRegDto.getSex());
        userInfo.setLastLogin(LocalDateTime.now());
        userInfo.setUserId(commonRemote.forAuth());

        userInfoRepository.save(userInfo);
        return true;

    }
}
